import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../utils/sava_cookie.dart';

class ApiClient {
  static final Dio dio = Dio(
    BaseOptions(
      baseUrl: 'http://www.fireferry.com/api',
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 5),
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    ),
  );

  static void init() {
    dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          // 从 SharedPreferences 中读取 cookie
          final prefs = await SharedPreferences.getInstance();
          final cookie = prefs.getString('cookie');

          // 如果 cookie 存在，添加到请求头
          if (cookie != null) {
            options.headers['Cookie'] = cookie;
          }
          return handler.next(options);
        },
        onResponse: (response, handler) async {
          // 保存新的 cookie
          saveCookie(response);
          return handler.next(response);
        },
        onError: (error, handler) async {
          // 处理错误
          return handler.next(error);
        },
      ),
    );
  }
}

class ApiEndpoints {
  static const String login = '/user/login';
  static const String getLoginStatus = '/user/get_login_status';
  static const String register = '/user/register';
  static const String logout = '/user/logout';
  static const String forgot_password = '/user/retrieve_password';
}
